package com.example.yijian.edit.watermarker;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.yijian.R;
import com.example.yijian.edit.data.BackupData;
import com.example.yijian.seletemedia.bean.MediaData;
import com.example.yijian.seletemedia.fragment.MediaFragment;
import com.example.yijian.seletemedia.interfaces.OnTotalNumChangeForActivity;
import com.example.yijian.seletemedia.view.CustomPopWindow;
import com.example.yijian.utils.AppManager;
import com.example.yijian.utils.Constants;
import com.example.yijian.utils.LogUtils;
import com.example.yijian.utils.MediaConstant;
import com.example.yijian.utils.PathUtils;
import com.example.yijian.utils.TimelineUtil;
import com.example.yijian.utils.ToastUtil;
import com.example.yijian.utils.Util;
import com.example.yijian.utils.asset.NvAsset;
import com.example.yijian.utils.asset.NvAssetManager;
import com.example.yijian.utils.datainfo.ClipInfo;
import com.example.yijian.utils.datainfo.TimelineData;
import com.meicam.effect.sdk.NvsEffectSdkContext;
import com.meicam.sdk.NvsStreamingContext;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import static com.example.yijian.utils.MediaConstant.KEY_CLICK_TYPE;
import static com.example.yijian.utils.MediaConstant.SINGLE_PICTURE_CLICK_CANCEL;
import static com.example.yijian.utils.MediaConstant.SINGLE_PICTURE_CLICK_CONFIRM;
import static com.example.yijian.utils.MediaConstant.SINGLE_PICTURE_CLICK_TYPE;
import static com.example.yijian.utils.MediaConstant.SINGLE_PICTURE_PATH;

public class SingleClickActivity extends AppCompatActivity implements OnTotalNumChangeForActivity, CustomPopWindow.OnViewClickListener {
    private static final String TAG = "SingleClickActivity";
    public NvAssetManager mAssetManager;
    public NvsStreamingContext mStreamingContext;
    public NvsEffectSdkContext mNvsEffectSdkContext;
    public Context mContext;

    private List<MediaData> mediaDataList;
    private int fromWhat = Constants.SELECT_IMAGE_FROM_WATER_MARK;
    /*
     * 画中画专用
     * Special for picture in picture
     * */
    private int mPicInPicVideoIndex = -1;

    private TextView tvTitle;
    private TextView singleTvStartEdit;
    private TextView singleTvCancel;
    private LinearLayout mGifToCafLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initCommonData();
        setContentView(R.layout.activity_single_click);
        initView();
        initData();
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        singleTvStartEdit = (TextView) findViewById(R.id.sigle_tv_startEdit);
        singleTvCancel = (TextView) findViewById(R.id.sigle_tv_cancel);
        mGifToCafLayout = (LinearLayout) findViewById(R.id.gifToCafLayout);
        mGifToCafLayout.setOnTouchListener((v, event) -> true);
        singleTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fromWhat == Constants.SELECT_PICTURE_FROM_BACKGROUND_SEG) {
                    Intent intent = new Intent();
                    intent.putExtra(SINGLE_PICTURE_CLICK_TYPE, SINGLE_PICTURE_CLICK_CANCEL);
                    setResult(RESULT_OK, intent);
                    AppManager.getInstance().finishActivity();
                }
            }
        });
        singleTvStartEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                singleTvStartEdit.setClickable(false);
                if (fromWhat == Constants.SELECT_IMAGE_FROM_WATER_MARK) {
                    Intent intent = new Intent();
                    intent.putExtra(SINGLE_PICTURE_PATH, mediaDataList.get(0).getPath());
                    setResult(RESULT_OK, intent);
                    finish();
                } else if (fromWhat == Constants.SELECT_PICTURE_FROM_BACKGROUND_SEG) {
                    if (mediaDataList == null || mediaDataList.size() == 0) {
                        ToastUtil.showToast(mContext, "请选择一个素材！");
                        singleTvStartEdit.setClickable(true);
                        return;
                    }
                    Intent intent = new Intent();
                    intent.putExtra(SINGLE_PICTURE_PATH, mediaDataList.get(0).getPath());
                    intent.putExtra(SINGLE_PICTURE_CLICK_TYPE, SINGLE_PICTURE_CLICK_CONFIRM);
                    setResult(RESULT_OK, intent);
                    AppManager.getInstance().finishActivity();
                } else if (fromWhat == Constants.SELECT_IMAGE_FROM_MAKE_COVER) {
                    new CustomPopWindow.PopupWindowBuilder(SingleClickActivity.this)
                            .setView(R.layout.pop_select_makesize)
                            .setViewClickListener(SingleClickActivity.this)
                            .create()
                            .showAtLocation(findViewById(android.R.id.content), Gravity.CENTER, 0, 0);
                } else if (fromWhat == Constants.SELECT_IMAGE_FROM_CUSTOM_STICKER) {
                    final String imageSrcFilePath = mediaDataList.get(0).getThumbPath();
                    int lastPointPos = imageSrcFilePath.lastIndexOf(".");
                    String fileSuffixName = imageSrcFilePath.substring(lastPointPos).toLowerCase();
                    if (fileSuffixName.equals(".gif")) {
                        /*
                         * 转圈，等待gif转caf
                         * Turn, wait for GIF to turn caf
                         * */
                        mGifToCafLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                gifToCafConvert(imageSrcFilePath);
                            }
                        }).start();
                    } else {//Image
                        Bundle bundle = new Bundle();
                        bundle.putString("imageSrcFilePath", imageSrcFilePath);
//                        AppManager.getInstance().jumpActivity(AppManager.getInstance().currentActivity(), CustomAnimateStickerActivity.class, bundle);
                    }
                } else if (fromWhat == Constants.FROMPICINPICACTIVITYTOVISIT) {
                    if (mPicInPicVideoIndex >= 0) {
                        /*
                         * 画中画页面，替换视频
                         * Picture-in-picture activity, replace video
                         * */
                        BackupData.instance().getPicInPicVideoArray().remove(mPicInPicVideoIndex);
                        BackupData.instance().getPicInPicVideoArray().add(mPicInPicVideoIndex, mediaDataList.get(0).getPath());
                        Intent intent = new Intent();
                        setResult(RESULT_OK, intent);
                        AppManager.getInstance().finishActivity();
                    }
                } else if (fromWhat == Constants.SELECT_PICTURE_FROM_BACKGROUND) {
                    Intent intent = new Intent();
                    intent.putExtra(SINGLE_PICTURE_PATH, mediaDataList.get(0).getThumbPath());
                    setResult(RESULT_OK, intent);
                    AppManager.getInstance().finishActivity();
                }
            }
        });

    }

    private void gifToCafConvert(String imageSrcFilePath) {
//        String gifName = imageSrcFilePath.substring(imageSrcFilePath.lastIndexOf("/"));
//        String converName = gifName.substring(0,gifName.lastIndexOf("."));
//        String gifContverDir = PathUtils.getGifConvertDir();
//        final String targetCafPath = gifContverDir + converName + ".caf";
//        NvRational frameRate = new NvRational(20, 1);
//        NvRational pixelAsprectRatio = new NvRational(1, 1);
//        NvCafCreator gifToCafCreator = new NvCafCreator(SingleClickActivity.this,
//                imageSrcFilePath, targetCafPath,
//                300, 300,
//                NvCafCreator.OUTPUT_FORMAT_PNG,
//                frameRate, pixelAsprectRatio,
//                NvCafCreator.OUTPUT_CAF_LOOP_MODE_REPEAT);
//        gifToCafCreator.setOnConvertListener(new NvCafCreator.OnConvertListener() {
//            @Override
//            public void convertBitmap(Bitmap bitmap) {
//                LogUtils.e(TAG, "cafConvert");
//            }
//
//            @Override
//            public void convertFinished(boolean ret) {
//                if (!ret) {
//                    LogUtils.e(TAG, "gif convert failed");
//                }else {
//                    LogUtils.e(TAG, "gif convert success");
//                }
//                Message message = m_handler.obtainMessage();
//                if(message == null)
//                    message = new Message();
//                Bundle bundle = new Bundle();
//                bundle.putString("imageSrcFilePath",imageSrcFilePath);
//                bundle.putString("targetCafPath",targetCafPath);
//                bundle.putBoolean("retResult",ret);
//                message.setData(bundle);
//                message.what = GIFTOCAFCONVERTFINISH;
//                m_handler.sendMessage(message);
//            }
//        });
//        gifToCafCreator.start();
//
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                fromWhat = bundle.getInt(Constants.SELECT_MEDIA_FROM, Constants.SELECT_IMAGE_FROM_WATER_MARK);
                mPicInPicVideoIndex = bundle.getInt("picInPicVideoIndex", -1);
                if (fromWhat == Constants.SELECT_VIDEO_FROM_DOUYINCAPTURE
                        || fromWhat == Constants.FROMPICINPICACTIVITYTOVISIT) {
                    /*
                     * 抖视频拍摄页面相册入口
                     * Video capture page album entry
                     * */
                    tvTitle.setText(getResources().getText(R.string.select_video));
                } else if (fromWhat == Constants.SELECT_PICTURE_FROM_BACKGROUND_SEG) {
                    singleTvCancel.setVisibility(View.VISIBLE);
                    singleTvCancel.setText("取消背景");
                    singleTvStartEdit.setVisibility(View.VISIBLE);
                    singleTvStartEdit.setText("设置背景");
                } else {
                    /*
                     * 封面, 水印,自定义贴纸
                     * Cover, watermark, custom sticker
                     * */
                    tvTitle.setText(getResources().getText(R.string.single_select_picture));
                }
            }
        }
        initVideoFragment(R.id.single_contain);
    }


    private void initVideoFragment(int layoutId) {
        MediaFragment mediaFragment = new MediaFragment();
        Bundle bundle = new Bundle();
        if (fromWhat == Constants.SELECT_VIDEO_FROM_DOUYINCAPTURE
                || fromWhat == Constants.FROMPICINPICACTIVITYTOVISIT) {
            /*
             * 抖视频拍摄页面相册入口或者画中画替换视频入口
             * Shake video capture page album entry or picture-in-picture replacement video entry
             * */
            bundle.putInt(MediaConstant.MEDIA_TYPE, MediaConstant.VIDEO);
        } else {
            /*
             * 封面, 水印,自定义贴纸
             * Cover, watermark, custom sticker
             * */
            bundle.putInt(MediaConstant.MEDIA_TYPE, MediaConstant.IMAGE);
        }
        bundle.putInt(KEY_CLICK_TYPE, MediaConstant.TYPE_ITEMCLICK_SINGLE);
        mediaFragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction()
                .add(layoutId, mediaFragment)
                .commit();
        getSupportFragmentManager().beginTransaction().show(mediaFragment);
    }


    private void initCommonData() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            LogUtils.e(TAG, "onCreate1111111111");
            finish();
            return;
        }
        mContext = this;
        mStreamingContext = getStreamingContext();
        mStreamingContext.stop();
        mNvsEffectSdkContext = getEffectContext();
    }

    public NvsStreamingContext getStreamingContext() {
        if (mStreamingContext == null) {
            synchronized (NvsStreamingContext.class) {
                if (mStreamingContext == null) {
                    mStreamingContext = NvsStreamingContext.getInstance();
                    if (mStreamingContext == null) {
                        String licensePath = "assets:/meishesdk.lic";
                        mStreamingContext = TimelineUtil.initStreamingContext(getApplicationContext(), licensePath);
                    }
                }
            }
        }
        return mStreamingContext;
    }

    public NvsEffectSdkContext getEffectContext() {
        if (mNvsEffectSdkContext == null) {
            synchronized (NvsEffectSdkContext.class) {
                if (mNvsEffectSdkContext == null) {
                    mNvsEffectSdkContext = NvsEffectSdkContext.getInstance();
                    if (mNvsEffectSdkContext == null) {
                        String licensePath = "assets:/meishesdk.lic";
                        mNvsEffectSdkContext = TimelineUtil.initEffectSdkContext(getApplicationContext(), licensePath);
                    }
                }
            }
        }
        return mNvsEffectSdkContext;
    }

    public NvAssetManager getNvAssetManager() {
        synchronized (NvAssetManager.class) {
            if (mAssetManager == null) {
                mAssetManager = NvAssetManager.sharedInstance();
                if (mAssetManager == null) {
                    mAssetManager = NvAssetManager.init(this);
                }
            }
        }
        return mAssetManager;
    }

    @Override
    public void onTotalNumChangeForActivity(List selectList, Object tag) {
        mediaDataList = selectList;
        singleTvStartEdit.setVisibility(selectList.size() > 0 ? View.VISIBLE : View.GONE);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onViewClick(CustomPopWindow popWindow, View view) {
        switch (view.getId()) {
            case R.id.button16v9:
                selectCreateRatio(Constants.POINT16V9);
                break;
            case R.id.button1v1:
                selectCreateRatio(Constants.POINT1V1);
                break;
            case R.id.button9v16:
                selectCreateRatio(Constants.POINT9V16);
                break;
            case R.id.button3v4:
                selectCreateRatio(Constants.POINT3V4);
                break;
            case R.id.button4v3:
                selectCreateRatio(Constants.POINT4V3);
                break;
            case R.id.button21v9:
                selectCreateRatio(Constants.POINT21V9);
                break;
            case R.id.button9v21:
                selectCreateRatio(Constants.POINT9V21);
                break;
            case R.id.button18v9:
                selectCreateRatio(Constants.POINT18V9);
                break;
            case R.id.button9v18:
                selectCreateRatio(Constants.POINT9V18);
            case R.id.button7v6:
                selectCreateRatio(Constants.POINT7V6);
                break;
            case R.id.button6v7:
                selectCreateRatio(Constants.POINT6V7);
                break;
            default:
                break;
        }
    }

    private void selectCreateRatio(int makeRatio) {
        ArrayList<ClipInfo> pathList = getClipInfoList();
        TimelineData.instance().setVideoResolution(Util.getVideoEditResolution(makeRatio));
        TimelineData.instance().setClipInfoData(pathList);
        TimelineData.instance().setMakeRatio(makeRatio);
//        AppManager.getInstance().jumpActivity(SingleClickActivity.this, MakeCoverActivity.class, null);
    }

    private ArrayList<ClipInfo> getClipInfoList() {
        ArrayList<ClipInfo> pathList = new ArrayList<>();
        if (mediaDataList != null) {
            for (MediaData mediaData : mediaDataList) {
                ClipInfo clipInfo = new ClipInfo();
                clipInfo.setImgDispalyMode(Constants.EDIT_MODE_PHOTO_TOTAL_DISPLAY);
                clipInfo.setOpenPhotoMove(false);
                clipInfo.setFilePath(mediaData.getPath());
                pathList.add(clipInfo);
            }
        }
        return pathList;
    }
}